//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2010
// by Perpetual Motion Interactive Systems Inc. ( http://www.perpetualmotion.ca )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.IO;
using System.Net;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Security.Roles;
namespace DotNetNuke.Modules.Admin.Sales
{
	partial class Purchase : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		private int RoleID = -1;

		private void InitializeComponent()
		{
		}
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			InitializeComponent();
		}
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			cmdPurchase.Click += new EventHandler(cmdPurchase_Click);
			cmdCancel.Click += new EventHandler(cmdCancel_Click);

			try
			{
				double dblTotal;
				string strCurrency;
				if ((Request.QueryString["RoleID"] != null))
				{
					RoleID = Int32.Parse(Request.QueryString["RoleID"]);
				}
				if (Page.IsPostBack == false)
				{
					RoleController objRoles = new RoleController();
					if (RoleID != -1)
					{
						RoleInfo objRole = objRoles.GetRole(RoleID, PortalSettings.PortalId);
						if (objRole.RoleID != -1)
						{
							lblServiceName.Text = objRole.RoleName;
							if (!Null.IsNull(objRole.Description))
							{
								lblDescription.Text = objRole.Description;
							}
							if (RoleID == PortalSettings.AdministratorRoleId)
							{
								if (!Null.IsNull(PortalSettings.HostFee))
								{
									lblFee.Text = PortalSettings.HostFee.ToString("#,##0.00");
								}
							}
							else
							{
								if (!Null.IsNull(objRole.ServiceFee))
								{
									lblFee.Text = objRole.ServiceFee.ToString("#,##0.00");
								}
							}
							if (!Null.IsNull(objRole.BillingFrequency))
							{
								Common.Lists.ListController ctlEntry = new Common.Lists.ListController();
								Common.Lists.ListEntryInfo entry = ctlEntry.GetListEntryInfo("Frequency", objRole.BillingFrequency);
								lblFrequency.Text = entry.Text;
							}
							txtUnits.Text = "1";
							if (objRole.BillingFrequency == "1")
							{
								txtUnits.Enabled = false;
							}
						}
						else
						{
							Response.Redirect(Common.Globals.NavigateURL(), true);
						}
					}
					if (Request.UrlReferrer != null)
					{
						ViewState["UrlReferrer"] = Convert.ToString(Request.UrlReferrer);
					}
					else
					{
						ViewState["UrlReferrer"] = "";
					}
				}
				if (RoleID == PortalSettings.AdministratorRoleId)
				{
					strCurrency = Host.HostCurrency;
				}
				else
				{
					strCurrency = PortalSettings.Currency;
				}
				dblTotal = Convert.ToDouble(lblFee.Text) * Convert.ToDouble(txtUnits.Text);
				lblTotal.Text = dblTotal.ToString("#.##");
				lblFeeCurrency.Text = strCurrency;
				lblTotalCurrency.Text = strCurrency;
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdPurchase_Click(System.Object sender, System.EventArgs e)
		{
			try
			{
				string strPaymentProcessor = "";
				string strProcessorUserId = "";
				string strProcessorPassword = "";
				if (Page.IsValid)
				{
					PortalController objPortalController = new PortalController();
					PortalInfo objPortalInfo = objPortalController.GetPortal(PortalSettings.PortalId);
					if (objPortalInfo != null)
					{
						strPaymentProcessor = objPortalInfo.PaymentProcessor;
						strProcessorUserId = objPortalInfo.ProcessorUserId;
						strProcessorPassword = objPortalInfo.ProcessorPassword;
					}
					if (strPaymentProcessor == "PayPal")
					{
						string strPayPalURL = "";
						strPayPalURL = "https://www.paypal.com/xclick/business=" + Common.Globals.HTTPPOSTEncode(strProcessorUserId);
						strPayPalURL = strPayPalURL + "&item_name=" + Common.Globals.HTTPPOSTEncode(PortalSettings.PortalName + " - " + lblDescription.Text + " ( " + txtUnits.Text + " units @ " + lblFee.Text + " " + lblFeeCurrency.Text + " per " + lblFrequency.Text + " )");
						strPayPalURL = strPayPalURL + "&item_number=" + Common.Globals.HTTPPOSTEncode(Convert.ToString(RoleID));
						strPayPalURL = strPayPalURL + "&quantity=1";
						strPayPalURL = strPayPalURL + "&custom=" + Common.Globals.HTTPPOSTEncode(UserInfo.UserID.ToString());
						strPayPalURL = strPayPalURL + "&amount=" + Common.Globals.HTTPPOSTEncode(lblTotal.Text);
						strPayPalURL = strPayPalURL + "&currency_code=" + Common.Globals.HTTPPOSTEncode(lblTotalCurrency.Text);
						strPayPalURL = strPayPalURL + "&return=" + Common.Globals.HTTPPOSTEncode("http://" + Common.Globals.GetDomainName(Request));
						strPayPalURL = strPayPalURL + "&cancel_return=" + Common.Globals.HTTPPOSTEncode("http://" + Common.Globals.GetDomainName(Request));
						strPayPalURL = strPayPalURL + "&notify_url=" + Common.Globals.HTTPPOSTEncode("http://" + Common.Globals.GetDomainName(Request) + "/admin/Sales/PayPalIPN.aspx");
						strPayPalURL = strPayPalURL + "&undefined_quantity=&no_note=1&no_shipping=1";
						Response.Redirect(strPayPalURL, true);
					}
				}
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		private void cmdCancel_Click(System.Object sender, System.EventArgs e)
		{
			try
			{
				Response.Redirect(Convert.ToString(ViewState["UrlReferrer"]), true);
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
		}
		double ConvertCurrency(string Amount, string FromCurrency, string ToCurrency)
		{
			string strPost = "Amount=" + Amount + "&From=" + FromCurrency + "&To=" + ToCurrency;
			StreamWriter objStream;
			double retValue = 0;
			try
			{
				HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://www.xe.com/ucc/convert.cgi");
				objRequest.Method = "POST";
				objRequest.ContentLength = strPost.Length;
				objRequest.ContentType = "application/x-www-form-urlencoded";
				objStream = new StreamWriter(objRequest.GetRequestStream());
				objStream.Write(strPost);
				objStream.Close();
				HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
				StreamReader sr;
				sr = new StreamReader(objResponse.GetResponseStream());
				string strResponse = sr.ReadToEnd();
				sr.Close();
				int intPos1 = strResponse.IndexOf(ToCurrency + "</B>");
				int intPos2 = strResponse.LastIndexOf("<B>", intPos1);
				retValue = Convert.ToDouble(strResponse.Substring(intPos2 + 3, (intPos1 - intPos2) - 4));
			}
			catch (Exception exc)
			{
				Services.Exceptions.Exceptions.ProcessModuleLoadException(this, exc);
			}
			return retValue;
		}
	}
}
